import React, { useMemo } from 'react';
import { 
  Card, 
  Tabs, 
  Empty, 
  Spin, 
  Typography, 
  Progress,
  Button,
  Space,
  Alert,
  Row,
  Col,
  Statistic,
  Divider
} from 'antd';
import {
  ExperimentOutlined,
  BarChartOutlined,
  ThunderboltOutlined,
  BulbOutlined,
  CheckOutlined,
  PlayCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import { useAnalysisContext, useAnalysisActions } from '../../context/AnalysisContext';
import ProblemTable from './ProblemTable';
import './AnalysisResults.css';

const { Text, Title, Paragraph } = Typography;

const AiAnalysisResults: React.FC = () => {
  const { state } = useAnalysisContext();
  const actions = useAnalysisActions();

  const {
    analysisResult,
    isAnalyzing,
    sqlContent,
    sourceDbType,
    targetDbType,
    activeTab,
    selectedIssueId
  } = state;

  // AI分析特有的统计数据
  const aiStatistics = useMemo(() => {
    if (!analysisResult) return null;
    
    const stats = analysisResult.statistics;
    const metadata = analysisResult.metadata;
    
    return {
      total: stats?.totalIssues || 0,
      high: stats?.highSeverityCount || 0,
      medium: stats?.mediumSeverityCount || 0,
      low: stats?.lowSeverityCount || 0,
      confidence: metadata?.confidence || 0,
      processingTime: metadata?.processingTime || 0,
      tokensUsed: metadata?.tokensUsed || 0,
      modelName: metadata?.modelName || 'Unknown'
    };
  }, [analysisResult]);

  // 分组后的问题列表
  const groupedProblems = useMemo(() => {
    if (!analysisResult?.issues) return [];

    const issues = analysisResult.issues;
    
    return [
      {
        key: 'HIGH',
        title: '高危问题',
        icon: <ThunderboltOutlined style={{ color: '#ff4d4f' }} />,
        count: issues.filter(i => i.severity === 'HIGH').length,
        items: issues.filter(i => i.severity === 'HIGH'),
        color: '#ff4d4f'
      },
      {
        key: 'MEDIUM',
        title: '中危问题',
        icon: <ThunderboltOutlined style={{ color: '#faad14' }} />,
        count: issues.filter(i => i.severity === 'MEDIUM').length,
        items: issues.filter(i => i.severity === 'MEDIUM'),
        color: '#faad14'
      },
      {
        key: 'LOW',
        title: '低危问题',
        icon: <InfoCircleOutlined style={{ color: '#1890ff' }} />,
        count: issues.filter(i => i.severity === 'LOW').length,
        items: issues.filter(i => i.severity === 'LOW'),
        color: '#1890ff'
      },
      {
        key: 'INFO',
        title: 'AI建议',
        icon: <BulbOutlined style={{ color: '#52c41a' }} />,
        count: issues.filter(i => i.severity === 'INFO').length,
        items: issues.filter(i => i.severity === 'INFO'),
        color: '#52c41a'
      }
    ].filter(group => group.count > 0);
  }, [analysisResult]);

  // 处理问题点击
  const handleIssueClick = (issue: any) => {
    actions.setSelectedIssueId(issue.id);
    actions.setCursorPosition({ 
      line: issue.lineNumber, 
      column: issue.columnNumber 
    });
  };

  // 处理Tab切换
  const handleTabChange = (key: string) => {
    actions.setActiveTab(key);
  };

  // 应用优化建议
  const handleApplyOptimization = () => {
    if (analysisResult?.optimizedSql) {
      actions.setSqlContent(analysisResult.optimizedSql);
    }
  };

  // 渲染AI统计信息
  const renderAiStatistics = () => {
    if (!aiStatistics) return null;

    return (
      <div className="analysis-stats">
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="识别问题"
              value={aiStatistics.total}
              valueStyle={{ color: aiStatistics.total > 0 ? '#ff4d4f' : '#52c41a' }}
              prefix={<ExperimentOutlined />}
            />
          </Col>
          <Col span={6}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>置信度</div>
              <Progress
                type="circle"
                size={60}
                percent={Math.round(aiStatistics.confidence * 100)}
                format={percent => `${percent}%`}
                strokeColor={aiStatistics.confidence > 0.8 ? '#52c41a' : aiStatistics.confidence > 0.6 ? '#faad14' : '#ff4d4f'}
              />
            </div>
          </Col>
          <Col span={6}>
            <Statistic
              title="处理时间"
              value={aiStatistics.processingTime / 1000}
              precision={2}
              suffix="s"
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Tokens"
              value={aiStatistics.tokensUsed}
              valueStyle={{ color: '#722ed1' }}
            />
          </Col>
        </Row>
        
        <div style={{ textAlign: 'center', marginTop: '8px' }}>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            模型: {aiStatistics.modelName}
          </Text>
        </div>
      </div>
    );
  };

  // 渲染优化建议
  const renderOptimization = () => {
    if (!analysisResult?.optimizedSql || !analysisResult?.optimizationExplanation) {
      return (
        <Empty 
          description="暂无优化建议" 
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      );
    }

    return (
      <div className="optimization-container" style={{ padding: '16px' }}>
        <div className="optimization-preview">
          <div style={{ marginBottom: '12px' }}>
            <Title level={5}>
              <BulbOutlined style={{ color: '#52c41a', marginRight: '8px' }} />
              AI优化建议
            </Title>
          </div>
          
          <Paragraph style={{ marginBottom: '16px' }}>
            {analysisResult.optimizationExplanation}
          </Paragraph>
          
          <div className="code-diff">
            <div className="original">
              <div style={{ marginBottom: '8px', fontWeight: 'bold', color: '#ff4d4f' }}>
                原始SQL:
              </div>
              <pre style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                {sqlContent.trim()}
              </pre>
            </div>
            
            <div className="optimized">
              <div style={{ marginBottom: '8px', fontWeight: 'bold', color: '#52c41a' }}>
                优化后SQL:
              </div>
              <pre style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                {analysisResult.optimizedSql.trim()}
              </pre>
            </div>
          </div>
          
          <div style={{ textAlign: 'center', marginTop: '16px' }}>
            <Button 
              type="primary" 
              icon={<CheckOutlined />}
              onClick={handleApplyOptimization}
            >
              应用优化建议
            </Button>
          </div>
        </div>
      </div>
    );
  };

  // 渲染空状态
  const renderEmptyState = () => {
    if (!sqlContent.trim()) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <ExperimentOutlined />
          </div>
          <div className="analysis-empty-text">
            请在左侧编辑器中输入SQL语句
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            AI将智能分析您的SQL并提供优化建议
          </Text>
        </div>
      );
    }

    if (sourceDbType === targetDbType) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <InfoCircleOutlined />
          </div>
          <div className="analysis-empty-text">
            源数据库和目标数据库相同
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            请选择不同的数据库类型进行AI分析
          </Text>
        </div>
      );
    }

    return (
      <div className="analysis-empty">
        <div className="analysis-empty-icon">
          <PlayCircleOutlined />
        </div>
        <div className="analysis-empty-text">
          点击"AI分析"按钮开始分析
        </div>
        <Text type="secondary" style={{ fontSize: '12px' }}>
          AI将智能识别兼容性问题并提供优化方案
        </Text>
      </div>
    );
  };

  // 渲染成功状态
  const renderSuccessState = () => (
    <div className="analysis-empty">
      <div className="analysis-empty-icon" style={{ color: '#52c41a' }}>
        <CheckOutlined />
      </div>
      <div className="analysis-empty-text">
        AI分析完成，未发现兼容性问题
      </div>
      <Text type="secondary" style={{ fontSize: '12px' }}>
        您的SQL语句在目标数据库中兼容性良好
      </Text>
    </div>
  );

  // Tab配置
  const tabItems = [
    {
      key: 'issues',
      label: (
        <Space>
          <ExperimentOutlined />
          AI识别问题
          {aiStatistics && aiStatistics.total > 0 && (
            <span className="tab-badge">{aiStatistics.total}</span>
          )}
        </Space>
      ),
      children: (
        <div className="problems-container">
          {groupedProblems.length > 0 ? (
            <ProblemTable
              problems={groupedProblems}
              selectedIssueId={selectedIssueId}
              onIssueClick={handleIssueClick}
            />
          ) : (
            renderSuccessState()
          )}
        </div>
      )
    },
    {
      key: 'optimization',
      label: (
        <Space>
          <BulbOutlined />
          优化建议
        </Space>
      ),
      children: renderOptimization()
    },
    {
      key: 'statistics',
      label: (
        <Space>
          <BarChartOutlined />
          AI分析统计
        </Space>
      ),
      children: (
        <div className="statistics-container">
          {aiStatistics ? (
            <div>
              {renderAiStatistics()}
              
              <Divider />
              
              <div>
                <Title level={5}>分析详情</Title>
                <Row gutter={[16, 16]}>
                  <Col span={24}>
                    <Alert
                      message="AI分析说明"
                      description={
                        <div>
                          <p>本次分析使用 {aiStatistics.modelName} 模型，基于深度学习技术识别SQL兼容性问题。</p>
                          <p>置信度: {Math.round(aiStatistics.confidence * 100)}% - {
                            aiStatistics.confidence > 0.8 ? '高置信度，建议采纳' :
                            aiStatistics.confidence > 0.6 ? '中等置信度，请仔细评估' :
                            '低置信度，建议人工复核'
                          }</p>
                          <p>处理时间: {(aiStatistics.processingTime / 1000).toFixed(2)}s，Token消耗: {aiStatistics.tokensUsed}</p>
                        </div>
                      }
                      type="info"
                      showIcon
                    />
                  </Col>
                </Row>
              </div>
            </div>
          ) : (
            <Empty description="暂无统计数据" />
          )}
        </div>
      )
    }
  ];

  return (
    <Card 
      className="results-section ai-analysis-results"
      title={
        <Space>
          <ExperimentOutlined />
          <span>AI分析结果</span>
          {isAnalyzing && <Spin size="small" />}
          {aiStatistics && (
            <Progress 
              size="small" 
              percent={Math.round(aiStatistics.confidence * 100)} 
              showInfo={false}
              strokeColor="#52c41a"
              style={{ width: '60px' }}
            />
          )}
        </Space>
      }
      size="small"
    >
      {isAnalyzing ? (
        <div className="analysis-loading">
          <Spin size="large" />
          <div style={{ marginTop: 16, textAlign: 'center' }}>
            <Text>AI正在分析您的SQL...</Text>
            <br />
            <Text type="secondary" style={{ fontSize: '12px' }}>
              这可能需要几秒钟时间
            </Text>
          </div>
        </div>
      ) : analysisResult ? (
        <div>
          {aiStatistics && aiStatistics.total > 0 && (
            <Alert
              message={`AI识别到 ${aiStatistics.total} 个潜在问题`}
              description={`分析置信度: ${Math.round(aiStatistics.confidence * 100)}%，建议仔细review分析结果`}
              type={aiStatistics.confidence > 0.8 ? 'success' : aiStatistics.confidence > 0.6 ? 'warning' : 'error'}
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}
          
          <Tabs
            activeKey={activeTab}
            onChange={handleTabChange}
            items={tabItems}
            size="small"
          />
        </div>
      ) : (
        renderEmptyState()
      )}
    </Card>
  );
};

export default AiAnalysisResults;